// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env:'mupp-5gs2863z7cf6873f'
})

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const db=cloud.database()
  const comment = db.collection('comment')
  const incomment = db.collection('incomment')
  const user = db.collection('user')
  let _id = event._id
  let openid = event.openid
  console.log(_id)
  let res = await comment.aggregate() //查询显示图片文章
  .match({
    _id:_id
  })
  .end()
  let getComment = res.list[0]
  console.log(getComment)
  let in_openid = getComment.openid  //文章作者的id
  let dz = getComment.dz
  let dianzan = 'dianzan.png'
  if(dz.indexOf(openid)>-1){   //判断这个文章是否有点赞
     dianzan = 'dianzan.png'
  }else{
     dianzan = 'aixin.png'
  }
  res = await incomment.aggregate() //查询显示评论
  .match({
    comment_pr_id:_id,
    parent_id:0
  })
  .end()
  console.log(res)
  let getInComment = res.list
  const _ = db.command

  res = await incomment.aggregate() //查询显示回复
  .match({
  comment_pr_id:_id,
  reply_id:_.gt(0)
  })
  .end()
  console.log(res)
  let getInComment2 = res.list

  res = await user.aggregate() //查询用户关注
  .match({
  openid:in_openid,
  })
  .end()
  console.log(res)
  let follow = res.list[0].follow
  let flow = '关注'
  if(follow.indexOf(openid)>-1){   //判断是否有关注这个作者
    flow = '已关注'
  }else{
    flow = '关注'
  }

  return {
    getComment,
    getInComment,
    getInComment2,
    dianzan,
    flow,
    follow
  }
}